package com.qf.commons.web.exception;

import com.qf.commons.base.result.Codes;
import com.qf.commons.base.result.R;
import com.qf.commons.base.result.Rs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * author Ken
 * create_time 2022/11/12
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 参数绑定异常的处理
     * @return
     */
    @ExceptionHandler(BindException.class)
    public R bindExceptionHandler(BindException e){
        //获取所有的绑定异常信息
        List<ObjectError> allErrors = e.getAllErrors();
        //准备一个绑定错误的信息集合
        List<String> errorInfo = new ArrayList<>();
        for (ObjectError allError : allErrors) {
            errorInfo.add(allError.getDefaultMessage());
        }
        return Rs.createFail(Codes.PARAM_BIND_ERROR, errorInfo);
    }

    @ExceptionHandler
    public R globalHandler(Throwable t){
        //记录日志
        log.error("[global exception] 发生了全局异常！", t);
        return Rs.createFail(Codes.FAIL);
    }
}
